package image

import (
	"context"
	"errors"
	"mime/multipart"
	"time"

	"go-weixin/app/guitar/api/internal/svc"
	"go-weixin/app/guitar/api/internal/types"
	"go-weixin/app/guitar/rpc/pb/proto/guitar"
	"go-weixin/common/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type GuitarImageAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	ut     utils.Utils
}

func NewGuitarImageAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GuitarImageAddLogic {
	return &GuitarImageAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		ut:     *utils.UT,
	}
}

func (l *GuitarImageAddLogic) GuitarImageAdd(req *types.GuitarImageAddReq, file multipart.File, fileHeader *multipart.FileHeader) (resp *types.GuitarImageAddResp, err error) {
	// 上传文件图片
	fileByte := make([]byte, fileHeader.Size)
	file.Read(fileByte)
	uploadRes, err := l.ut.GoFastDfs.GoFastDfsClient(fileByte, fileHeader.Filename, fileHeader.Size, l.svcCtx.Config.GoFast.DNS)
	if err != nil {
		return nil, errors.New("guitar.image.add文件上传:" + err.Error())
	}
	ctx, cannFunc := context.WithTimeout(context.Background(), time.Second*5)
	defer cannFunc()
	_, err = l.svcCtx.GuitarRPC.GuitarImageAdd(ctx, &guitar.GuitarImageAddReq{
		GuitarId: req.GuitarId,
		Url:      uploadRes.Path,
	})
	resp = new(types.GuitarImageAddResp)
	resp.Url = uploadRes.Path
	return
}
